package utils;

public class LinkListUtil {

    /**
     * 生成随机单链表
     */
    public static ListNode generateRandomList(int length, int maxValue, boolean randomLength) {
        if (length == 0) {
            return null;
        }
        if (randomLength) {
            length = (int) (Math.random() * (length + 1));
        }
        ListNode head = new ListNode((int) (Math.random() * (maxValue + 1)));
        ListNode pre = head;
        while (length > 0) {
            ListNode listNode = new ListNode((int) (Math.random() * (maxValue + 1)));
            pre.next = listNode;
            pre = listNode;
            length--;
        }
        return head;
    }

    /**
     * 生成随机双链表
     */
    public static DoubleNode generateDoubleRandomList(int length, int maxValue, boolean randomLength) {
        if (length == 0) {
            return null;
        }
        if (randomLength) {
            length = (int) (Math.random() * (length - 1));
        }
        DoubleNode head = new DoubleNode((int) (Math.random() * (maxValue + 1)));
        DoubleNode pre = head;
        while (length > 0) {
            DoubleNode node = new DoubleNode((int) (Math.random() * (maxValue + 1)));
            pre.next = node;
            node.last = pre;
            pre = node;
            length--;
        }
        return head;
    }

    /**
     * 单链表转成数组
     */
    public static int[] linkListToArray(ListNode head, int length) {
        if (head == null) {
            return null;
        }
        int[] ans = new int[length];
        int i = 0;
        ListNode copyHead = copyNode(head);
        while (copyHead != null) {
            ans[i] = copyHead.value;
            copyHead = copyHead.next;
            i++;
        }
        return ans;
    }

    /**
     * 打印单链表
     */
    public static void printLinkList(ListNode head) {
        ListNode copyHead = copyNode(head);
        while (copyHead != null) {
            System.out.print(copyHead.value + ",");
            copyHead = copyHead.next;
        }
        System.out.println("");
    }

    /**
     * 打印双链表
     */
    public static void printDoubleLinkList(DoubleNode head) {
        DoubleNode copyHead = copyNode(head);
        while (copyHead != null) {
            System.out.print(copyHead.value + ",");
            copyHead = copyHead.next;
        }
        System.out.println("");
    }

    /**
     * 复制一个头节点返回，原头节点不要消失
     *
     * @param listNode
     * @return
     */
    public static ListNode copyNode(ListNode listNode) {
        return new ListNode(listNode.value, listNode.next);
    }

    public static DoubleNode copyNode(DoubleNode node) {
        return new DoubleNode(node.value, node.next, node.last);
    }
}
